package org.banyan.senior.idempotent.bean;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author metalsbanyan
 * @version 1.0
 * @description: 自定义可重复读的 HttpServletRequest InputStream， 注意，需要在filter中替换掉
 * @date 2023/7/22 10:53
 */
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private final String body;

    public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        request.setCharacterEncoding("UTF-8");
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        this.body = sb.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 使用已有的 字符串 构造一个输入流返回给程序调用
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public int available() {
                return body.length();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    public String getBody() {
        return body;
    }
}
